#inspired from https://github.com/shawwwn/micropython-ainput/blob/master/uaioinput.py
# MIT / Copyright (c) 2018 Shawwwn <shawwwn1@gmai.com>

import os
from asyncio.synchro import Lock

Lock = Lock()
UART = __import__('machine').UART(0)

async def ainput(prompt=None, password=False):
    global Lock

    def switch(input=None):
        global UART
        if input is not None:
            #os.dupterm( UART , 1)
            sys.stdout.write(input)
        os.dupterm( None , 1)

    input = __import__('uio').StringIO()
    input.seek(0)
    tell = 0
    current = prompt

    await Lock.acquire()
    switch(current)

    try:
        while use.lives:
            if UART.any():
                current = UART.read(1)
                chr = ord(current)
                if 31<chr<127:
                    input.seek(tell)
                    input.write(current)
                    tell += 1
                elif chr==127:
                    tell -= 1 if tell>0 else 0
                elif chr in [13,10]: #???? flush 10 ?
                    sys.stdout.write(b'\n')
                    current = None
                    break
                switch(current)
                current = None
            await aio.asleep_ms(1)

        input.seek(0)
        aio.loop.call_soon(aio.loop.stop)
        return input.read(tell)
    finally:
        Lock.release()
        os.dupterm( UART , 1)


async def test():
    print()
    print('awaiting input >>> ')
    data = await ainput()
    print()
    print('='*40)
    print(data)

